package com.lzy.ninegrid.preview;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.lzy.ninegrid.ActionSheet;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.NineGridViewImgUtils;
import com.lzy.ninegrid.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

import static android.content.Context.WINDOW_SERVICE;

/**
 * ================================================
 * 作    者：廖子尧
 * 版    本：1.0
 * 创建日期：2016/3/21
 * 描    述：用来给Imageview加载item视图的适配器
 * 修订历史：
 * 增加长按图片保存 by:liu
 * ================================================
 */
public class ImagePreviewAdapter extends PagerAdapter implements PhotoViewAttacher.OnPhotoTapListener, ActionSheet.OnSheetItemClickListener {

    private List<ImageInfo> imageInfo;
    private Context context;
    private View currentView;
    private ImageInfo mInfo;
    private String dirName;
    private File file;
    private String fileName;
    private static final String TAG = "ImagePreviewAdapter";

    public ImagePreviewAdapter(Context context, @NonNull List<ImageInfo> imageInfo) {
        super();
        this.imageInfo = imageInfo;
        this.context = context;
    }

    @SuppressLint("HandlerLeak")
    @Override
    public int getCount() {
        return imageInfo.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        currentView = (View) object;
    }

    public View getPrimaryItem() {
        return currentView;
    }

    public ImageView getPrimaryImageView() {
        return (ImageView) currentView.findViewById(R.id.pv);
    }

    public SubsamplingScaleImageView getSubImageView() {

        return (SubsamplingScaleImageView) currentView.findViewById(R.id.pv_long);
    }


    /**
     * 实例化item  有时候失败
     *
     * @param container
     * @param position
     * @return
     */
    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {

        Log.i(TAG, "开始实例化item" + position);
        final ImageInfo info = this.imageInfo.get(position);

        boolean isLongImage = info.getImageHeight() > 5000 && info.getImageHeight() / info.getImageWidth() >= 2;
        View convertView;
        int layoutId;
        String bigImageUrl = info.getBigImageUrl();

        if (isLongImage) {
            layoutId = R.layout.item_long_subimageview;
            convertView = LayoutInflater.from(context).inflate(layoutId, container, false);
            final ProgressBar pbLong = convertView.findViewById(R.id.pb_long);
            final SubsamplingScaleImageView subsamplingScaleImageView = convertView.findViewById(R.id.pv_long);
            // 轻触退出事件  长图
            subsamplingScaleImageView.setOnClickListener(new SubsamplingScaleImageView.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "点击退出");
                    ((ImagePreviewActivity) context).finishActivityAnim();
                }
            });

            //开始网络加载图片 长图加载
            NineGridView.getImageLoader().onDisplayImage(convertView.getContext(), subsamplingScaleImageView, bigImageUrl);
            //开始加载过度图片   有误
            showExcessPic(info, subsamplingScaleImageView);
            subsamplingScaleImageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    showSaveMenu(context, info);
                    return false;
                }
            });
        } else {
            layoutId = R.layout.item_photoview;
            convertView = LayoutInflater.from(context).inflate(layoutId, container, false);
            final ProgressBar pb = convertView.findViewById(R.id.pb);
            final PhotoView imageView = convertView.findViewById(R.id.pv);
            imageView.setOnPhotoTapListener(this);

            //开始网络加载图片 普通加载
            NineGridView.getImageLoader().onDisplayImage(convertView.getContext(), imageView, bigImageUrl);
            showExcessPic(info, imageView);

            imageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    showSaveMenu(context, info);
                    return false;
                }
            });
        }

//        pb.setVisibility(View.VISIBLE);
//        Glide.with(context).load(info.bigImageUrl)//
//                .placeholder(R.drawable.ic_default_image)//
//                .error(R.drawable.ic_default_image)//
//                .diskCacheStrategy(DiskCacheStrategy.ALL)//
//                .listener(new RequestListener<String, GlideDrawable>() {
//                    @Override
//                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
//                        pb.setVisibility(View.GONE);
//                        return false;
//                    }
//
//                    @Override
//                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//                        pb.setVisibility(View.GONE);
//                        return false;
//                    }
//                }).into(imageView);

        //长按保存事件
        container.addView(convertView);
        return convertView;
    }

    private void showSaveMenu(Context context, ImageInfo info) {
        mInfo = info;
        ActionSheet actionSheet = new ActionSheet(context);
        actionSheet.builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("保存图片", ActionSheet.SheetItemColor.Blue, this)
                .show();
    }

    @Override
    public void onClick(int which) {
        switch (which) {
            case 1:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        download(mInfo);
                    }
                }).start();
                Toast.makeText(context, "图片保存成功", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    private void download(ImageInfo info) {
        try {
            URL url = new URL(info.getBigImageUrl());
            //打开连接
            URLConnection conn = url.openConnection();
            //打开输入流
            InputStream is = conn.getInputStream();
            //获得长度
            int contentLength = conn.getContentLength();
            //创建文件夹，在存储卡下
            dirName = Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/";
            file = new File(dirName);
            //不存在创建
            if (!file.exists()) {
                file.mkdirs();
            }
            //获取文件后缀名
            String fileNameFromUrl = NineGridViewImgUtils.getFileName(info.getBigImageUrl());
            String type = fileNameFromUrl.substring(fileNameFromUrl.lastIndexOf(".") + 1);
            //下载后的文件名
            this.fileName = dirName + System.currentTimeMillis() + "." + type;
            File file1 = new File(this.fileName);
            if (file1.exists()) {
                file1.delete();     //不能有同名文件
            }
            //创建字节流
            byte[] bs = new byte[1024];
            int len;
            OutputStream os = new FileOutputStream(this.fileName);
            //写数据
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            //完成后关闭流
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + dirName)));

    }

    /**
     * 展示大图过渡图片
     */
    private void showExcessPic(ImageInfo imageInfo, SubsamplingScaleImageView imageView) {
        Log.i(TAG, "大图过渡" + imageView);
        String bigImageUrl = imageInfo.getBigImageUrl();
        Bitmap cacheImage = NineGridView.getImageLoader().getCacheImage(bigImageUrl);
        //如果大图的缓存不存在,在获取小图的缓存
        if (cacheImage == null) {
            String thumbnailUrl = imageInfo.getThumbnailUrl();
            cacheImage = NineGridView.getImageLoader().getCacheImage(thumbnailUrl);
        }
        //如果没有任何缓存,使用默认图片,否者使用缓存
        if (cacheImage == null) {
            //错误！！！这个逻辑判断有错误
            //imageView.setImage(ImageSource.resource(R.drawable.actionsheet_bottom_pressed));
        } else {
            //sub可以添加uri,bitmap,int,asset
            imageView.setImage(ImageSource.bitmap(cacheImage));
            //bitmap被回收
            cacheImage.recycle();
        }
    }

    /**
     * 展示过度图片
     */
    private void showExcessPic(ImageInfo imageInfo, PhotoView imageView) {
        String bigImageUrl = imageInfo.getBigImageUrl();
        Bitmap cacheImage = NineGridView.getImageLoader().getCacheImage(bigImageUrl);
        //如果大图的缓存不存在,在获取小图的缓存
        if (cacheImage == null) {
            String thumbnailUrl = imageInfo.getThumbnailUrl();
            cacheImage = NineGridView.getImageLoader().getCacheImage(thumbnailUrl);
        }
        //如果没有任何缓存,使用默认图片,否者使用缓存
        if (cacheImage == null) {
            imageView.setImageResource(R.drawable.ic_default_color);
        } else {
            imageView.setImageBitmap(cacheImage);
            //bitmap被回收
            cacheImage.recycle();
        }
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        //滑动崩溃
        //super.destroyItem(container, position, object);
        container.removeView((View) object);
    }

    /**
     * 单击屏幕关闭
     * 长图不能绑定此方法
     */
    @Override
    public void onPhotoTap(View view, float x, float y) {
        Log.i(TAG, "单击" + view + " " + x + " " + y);
        ((ImagePreviewActivity) context).finishActivityAnim();
    }
}